<template>
  <view class="quotation-container">


    <!-- 报价卡片 -->
    <view class="quotation-card">
      <view class="card-header">
        <view class="header-indicator"></view>
        <text class="card-title">请输入您的报价</text>
      </view>
      
      <view class="price-input-wrapper">
        <text class="currency-symbol">¥</text>
        <input 
          class="price-input" 
          type="digit"
          placeholder="请输入金额"
          v-model="quotationPrice"
          :focus="inputFocus"
          @input="onPriceInput"
          @focus="onInputFocus"
          @blur="onInputBlur"
        />
        <text class="unit-text">/天</text>
      </view>
      
      <view class="tips">
        <text class="tips-text">* 请合理报价，报价过高可能影响推荐成功率</text>
      </view>
    </view>

    <!-- 底部按钮区域 -->
    <view class="footer">
      <view class="cancel-btn" @click="cancelQuotation">
        <text>取消报价</text>
      </view>
      <view class="confirm-btn" @click="confirmQuotation" :class="{ disabled: !quotationPrice }">
        <text>确认报价</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useProjectStore } from '/stores/project.js'
import { useUserStore } from '/pages/store/user.js'
import { apiService } from '/pages/utils/api.js'

const quotationPrice = ref('')
const inputFocus = ref(false)

// 存储传递过来的参数
const pageParams = ref({})

// 使用项目store和用户store
const projectStore = useProjectStore()
const userStore = useUserStore()

onLoad((options) => {
  console.log('报价页面加载完成', options)
  
  // 初始化用户状态
  userStore.initUserState()
  
  // 设置导航栏标题
  projectStore.setNavigationTitle()
  
  // 保存传递过来的参数
  pageParams.value = {
    roleArr: options.roleArr || '',
    min: options.min || '',
    classify: options.classify || '',
    projectId: options.projectId || '',
    roleType: options.roleType || '',
    detailsId: options.detailsId || ''

  }
  console.log('接收到的页面参数:', pageParams.value)
  console.log('arr');
  
  // 安全解析 roleArr，避免空字符串导致的 JSON 解析错误
  try {
    if (pageParams.value.roleArr && pageParams.value.roleArr.trim() !== '') {
      // 对双重编码的参数进行解码
      let decodedRoleArr = decodeURIComponent(pageParams.value.roleArr);
      console.log('解码后的 roleArr:', decodedRoleArr);
      console.log('解析的候选人数组:', JSON.parse(decodedRoleArr));
    } else {
      console.log('roleArr 为空，跳过解析');
    }
  } catch (error) {
    console.error('解析 roleArr 失败:', error);
    console.log('原始 roleArr 值:', pageParams.value.roleArr);
  }
  
  
})


// 返回上一页
const goBack = () => {
  uni.navigateBack({
    delta: 1
  })
}

// 价格输入处理
const onPriceInput = (e) => {
  let value = e.detail.value
  // 只允许输入数字和小数点，最多两位小数
  value = value.replace(/[^\d.]/g, '')
  if (value.split('.').length > 2) {
    value = value.substring(0, value.lastIndexOf('.'))
  }
  if (value.includes('.')) {
    const parts = value.split('.')
    if (parts[1] && parts[1].length > 2) {
      value = parts[0] + '.' + parts[1].substring(0, 2)
    }
  }
  quotationPrice.value = value
}

// 输入框聚焦
const onInputFocus = () => {
  inputFocus.value = true
}

// 输入框失焦
const onInputBlur = () => {
  inputFocus.value = false
}

// 取消报价
const cancelQuotation = () => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消报价吗？',
    confirmText: '确定',
    cancelText: '继续报价',
    confirmColor: '#ff6a9c',
    success: (res) => {
      if (res.confirm) {
        goBack()
      }
    }
  })
}

// 确认报价
const confirmQuotation = () => {
  if (!quotationPrice.value) {
    uni.showToast({
      title: '请输入报价金额',
      icon: 'none'
    })
    return
  }

  const price = parseFloat(quotationPrice.value)
  if (price <= 0) {
    uni.showToast({
      title: '请输入有效金额',
      icon: 'none'
    })
    return
  }

  uni.showModal({
    title: '确认报价',
    content: `确认报价 ¥${quotationPrice.value}/天 吗？`,
    confirmText: '确认',
    cancelText: '修改',
    confirmColor: '#ff6a9c',
    success: (res) => {
      if (res.confirm) {
        // 提交报价逻辑
        submitQuotation()
      }
    }
  })
}

// 提交报价
const submitQuotation = async () => {
  uni.showLoading({
    title: '提交中...'
  })

  // 获取当前登录用户的rowid
  const userRowid = userStore.rowid || uni.getStorageSync('rowid')
  
  if (!userRowid) {
    uni.hideLoading()
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    uni.navigateTo({
      url: '/pages/login/login'
    })
    return
  }
  
  // 安全解析 roleArr
  let parsedRoleArr = []
  try {
    if (pageParams.value.roleArr && pageParams.value.roleArr.trim() !== '') {
      // 对双重编码的参数进行解码
      const decodedRoleArr = decodeURIComponent(pageParams.value.roleArr)
      parsedRoleArr = JSON.parse(decodedRoleArr)
    }
  } catch (error) {
    console.error('解析 roleArr 失败:', error)
    uni.hideLoading()
    uni.showToast({
      title: '参数错误，请重新选择',
      icon: 'none'
    })
    return
  }
  
  console.log('提交报价参数:', {
    roleArr: parsedRoleArr,
    price: quotationPrice.value,
    rowid: userRowid,
    projectId: pageParams.value.projectId,
     DetailsId: pageParams.value.detailsId
  })
  
  const res = await apiService.quotation({
    roleArr: parsedRoleArr,
    price: quotationPrice.value,
    rowid: userRowid,
    projectId: pageParams.value.projectId,
    DetailsId: pageParams.value.detailsId
  })
  console.log('res');
  
  console.log(res);

  // 模拟API调用
  setTimeout(() => {
    uni.hideLoading()
    uni.showToast({
      title: '报价提交成功',
      icon: 'success',
      duration: 2000
    })
    
    // 2秒后回退到position.vue页面
    setTimeout(() => {
      // 根据角色类型决定回退层级
      const classify = pageParams.value.classify || ''
      
      if (classify === "一类角色") {
        // 一类角色：quotation -> candidate/index -> content -> position (回退3层)
        console.log('一类角色，回退3层到position页面')
        uni.navigateBack({
          delta: 3
        })
      } else {
        // 二类角色：quotation -> content -> position (回退2层)
        console.log('二类角色，回退2层到position页面')
        uni.navigateBack({
          delta: 2
        })
      }
    }, 2000)
  }, 1500)
}
</script>

<style lang="scss" scoped>
.quotation-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  padding-bottom: 80px; /* 为底部按钮留出空间 */
}

/* 顶部标题栏 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;
  background-color: #fff;
  padding: 0 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 100;

  .back-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    
    .icon-back {
      font-size: 24px;
      color: #333;
      font-weight: bold;
    }
  }

  .title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }

  .placeholder {
    width: 40px;
  }
}

/* 报价卡片 */
.quotation-card {
  background-color: #fff;
  border-radius: 16px;
  margin: 20px 15px;
  padding: 30px 20px;
  box-shadow: 0 4px 12px rgba(255, 106, 156, 0.1);
  border: 1px solid #f9cde3;

  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 30px;

    .header-indicator {
      width: 4px;
      height: 20px;
      background-color: #ff6a9c;
      border-radius: 2px;
      margin-right: 10px;
    }

    .card-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  .price-input-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff8fc;
    border: 2px solid #f9cde3;
    border-radius: 12px;
    padding: 20px 15px;
    margin-bottom: 15px;
    position: relative;

    &:focus-within {
      border-color: #ff6a9c;
      box-shadow: 0 0 0 3px rgba(255, 106, 156, 0.1);
    }

    .currency-symbol {
      font-size: 24px;
      color: #ff6a9c;
      font-weight: 600;
      margin-right: 5px;
    }

    .price-input {
      flex: 1;
      font-size: 32px;
      color: #333;
      text-align: center;
      background-color: transparent;
      border: none;
      outline: none;
      font-weight: 600;

      &::placeholder {
        color: #ccc;
        font-size: 16px;
      }
    }

    .unit-text {
      font-size: 16px;
      color: #666;
      margin-left: 5px;
    }
  }

  .tips {
    text-align: center;

    .tips-text {
      font-size: 12px;
      color: #999;
      line-height: 1.4;
    }
  }
}

/* 底部按钮区域 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;

  .cancel-btn {
    flex: 1;
    height: 45px;
    border: 1px solid #ddd;
    border-radius: 25px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    margin-right: 10px;
    font-size: 16px;
    color: #333;
    transition: all 0.3s ease;

    &:active {
      background-color: #f5f5f5;
    }
  }

  .confirm-btn {
    flex: 1;
    height: 45px;
    background: linear-gradient(to right, #ff6a9c, #ff9e9e);
    border-radius: 25px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #fff;
    margin-left: 10px;
    transition: all 0.3s ease;

    &.disabled {
      background: #ccc;
      opacity: 0.6;
    }

    &:not(.disabled):active {
      transform: scale(0.98);
    }
  }
}
</style>
